-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathstatic_plots.py
executable file
·1566 lines (1430 loc) · 50.2 KB
/
static_plots.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
from plotnine import (
ggsave,
ggplot,
aes,
geom_histogram,
scale_color_discrete,
element_blank,
theme,
xlab,
scale_fill_manual,
scale_color_cmap,
coord_cartesian,
ylab,
scale_x_continuous,
scale_y_continuous,
geom_tile,
coord_fixed,
facet_grid,
labs,
element_line,
element_text,
theme_light,
geom_blank,
annotate,
element_rect,
coord_flip,
theme_minimal,
geom_raster,
)
import cairosvg
import pandas as pd
import numpy as np
from PIL import Image
import patchworklib as pw
import math
import os
import xml.etree.ElementTree as ET
import sys
import re
from moddotplot.parse_fasta import printProgressBar
from moddotplot.const import (
DIVERGING_PALETTES,
QUALITATIVE_PALETTES,
SEQUENTIAL_PALETTES,
)
from typing import List
from palettable.colorbrewer import qualitative, sequential, diverging
def is_plot_empty(p):
# Check if the plot has data or any layers
return len(p.layers) == 0 and p.data.empty
def check_pascal(single_val, double_val):
try:
if len(single_val) == 2:
assert len(double_val) == 1
elif len(single_val) == 3:
assert len(double_val) == 3
elif len(single_val) == 4:
assert len(double_val) == 6
elif len(single_val) == 5:
assert len(double_val) == 10
elif len(single_val) == 6:
assert len(double_val) == 15
elif len(single_val) == 0:
assert len(double_val) == (1 or 3 or 6 or 10 or 15)
except AssertionError as e:
print(
f"Missing bed files required to create grid. Please verify all bed files are included."
)
sys.exit(8)
def reverse_pascal(double_vals):
if len(double_vals) == 1:
return 2
elif len(double_vals) == 3:
return 3
elif len(double_vals) == 6:
return 4
elif len(double_vals) == 10:
return 5
elif len(double_vals) == 15:
return 6
else:
sys.exit(9)
# Hardcoding for now, I have the formula.... I'm just lazy
def transpose_order(double_vals):
if len(double_vals) == 1:
return [0]
elif len(double_vals) == 3:
return [0, 1, 2]
elif len(double_vals) == 6:
return [0, 1, 3, 2, 4, 5]
elif len(double_vals) == 10:
return [0, 1, 4, 2, 5, 7, 3, 6, 8, 9]
elif len(double_vals) == 15:
return [0, 1, 5, 2, 6, 9, 3, 7, 10, 12, 4, 8, 11, 13, 14]
def check_st_en_equality(df):
unequal_rows = df[(df["q_st"] != df["r_st"]) | (df["q_en"] != df["r_en"])]
unequal_rows.loc[:, ["q_en", "r_en", "q_st", "r_st"]] = unequal_rows[
["r_en", "q_en", "r_st", "q_st"]
].values
df = pd.concat([df, unequal_rows], ignore_index=True)
return df
def make_k(vals):
return [number / 1000 for number in vals]
def make_m(vals):
return [number / 1e6 for number in vals]
def make_g(vals):
return [number / 1e9 for number in vals]
def make_scale(vals: list) -> list:
scaled = [number for number in vals]
if scaled[-1] < 200000:
return make_k(scaled)
elif scaled[-1] > 200000000:
return make_g(scaled)
else:
return make_m(scaled)
def overlap_axis(rotated_plot, filename, prefix):
scale_factor = math.sqrt(2) + 0.04
new_width = int(rotated_plot.width / scale_factor)
new_height = int(rotated_plot.height / scale_factor)
resized_rotated_plot = rotated_plot.resize((new_width, new_height), Image.LANCZOS)
# Step 3: Overlay the resized rotated heatmap onto the original axes
# Open the original heatmap with axes
image_with_axes = Image.open(filename)
# Create a blank image with the same size as the original
final_image = Image.new("RGBA", image_with_axes.size)
# Calculate the position to center the resized rotated image within the original plot area
x_offset = (final_image.width - resized_rotated_plot.width) // 2
y_offset = (final_image.height - resized_rotated_plot.height) // 2
y_offset += 2400
x_offset += 30
# Paste the original image with axes onto the final image
final_image.paste(image_with_axes, (0, 0))
# Paste the resized rotated plot onto the final image
final_image.paste(resized_rotated_plot, (x_offset, y_offset), resized_rotated_plot)
width, height = final_image.size
cropped_image = final_image.crop((0, height // 2.6, width, height))
# Save or show the final image
cropped_image.save(f"{prefix}_TRI.png")
cropped_image.save(f"{prefix}_TRI.pdf", "PDF", resolution=100.0)
# Remove temp files
if os.path.exists(filename):
os.remove(filename)
def get_colors(sdf, ncolors, is_freq, custom_breakpoints):
assert ncolors > 2 and ncolors < 12
try:
bot = math.floor(min(sdf["perID_by_events"]))
except ValueError:
bot = 0
top = 100.0
interval = (top - bot) / ncolors
breaks = []
if is_freq:
breaks = np.unique(
np.quantile(sdf["perID_by_events"], np.arange(0, 1.01, 1 / ncolors))
)
else:
breaks = [bot + i * interval for i in range(ncolors + 1)]
if custom_breakpoints:
breaks = np.asfarray(custom_breakpoints)
labels = np.arange(len(breaks) - 1)
# corner case of only one %id value
if len(breaks) == 1:
return pd.factorize([1] * len(sdf["perID_by_events"]))[0]
else:
tmp = pd.cut(
sdf["perID_by_events"], bins=breaks, labels=labels, include_lowest=True
)
return tmp
# TODO: Remove pandas dependency
def read_df_from_file(file_path):
data = pd.read_csv(file_path, delimiter="\t")
return data
def read_df(
pj,
palette,
palette_orientation,
is_freq,
custom_colors,
custom_breakpoints,
from_file,
):
df = ""
if from_file is not None:
df = from_file
else:
data = pj[0]
df = pd.DataFrame(data[1:], columns=data[0])
hexcodes = []
new_hexcodes = []
if palette in DIVERGING_PALETTES:
function_name = getattr(diverging, palette)
hexcodes = function_name.hex_colors
if palette_orientation == "+":
palette_orientation = "-"
else:
palette_orientation = "+"
elif palette in QUALITATIVE_PALETTES:
function_name = getattr(qualitative, palette)
hexcodes = function_name.hex_colors
elif palette in SEQUENTIAL_PALETTES:
function_name = getattr(sequential, palette)
hexcodes = function_name.hex_colors
else:
print(f"Palette {palette} not found. Defaulting to Spectral_11.\n")
function_name = getattr(diverging, "Spectral_11")
palette_orientation = "-"
hexcodes = function_name.hex_colors
if palette_orientation == "-":
new_hexcodes = hexcodes[::-1]
else:
new_hexcodes = hexcodes
if custom_colors:
new_hexcodes = custom_colors
ncolors = len(new_hexcodes)
# Get colors for each row based on the values in the dataframe
df["discrete"] = get_colors(df, ncolors, is_freq, custom_breakpoints)
# Rename columns if they have different names in the dataframe
if "query_name" in df.columns or "#query_name" in df.columns:
df.rename(
columns={
"#query_name": "q",
"query_start": "q_st",
"query_end": "q_en",
"reference_name": "r",
"reference_start": "r_st",
"reference_end": "r_en",
},
inplace=True,
)
# Calculate the window size
try:
window = max(df["q_en"] - df["q_st"])
except ValueError:
window = 0
# Calculate the position of the first and second intervals
df["first_pos"] = df["q_st"] / window
df["second_pos"] = df["r_st"] / window
return df
def generate_breaks(number, min_breaks=5, max_breaks=9):
# Determine the order of magnitude
magnitude = 10 ** int(
math.floor(math.log10(number))
) # Base power of 10 (e.g., 10M, 1M, 100K)
threshold = math.ceil(number / magnitude)
while threshold > max_breaks:
magnitude *= 2
threshold = math.ceil(number / magnitude)
while threshold < min_breaks:
magnitude /= 2
threshold = math.ceil(number / magnitude)
# Generate breakpoints
breaks = list(range(0, int((threshold * magnitude) + magnitude), int(magnitude)))
return breaks
def make_dot(
sdf,
name_x,
name_y,
palette,
palette_orientation,
colors,
breaks,
num_ticks,
xlim,
deraster,
width,
is_pairwise,
):
if is_pairwise:
title_name = f"Comparative Plot: {name_x} vs {name_y}"
else:
title_name = f"Self-Identity Plot: {name_x}"
title_length = 2 * width
if len(title_name) > 50:
title_length = 1.5 * width
elif len(title_name) > 80:
title_length = width
# Select the color palette
if hasattr(diverging, palette):
function_name = getattr(diverging, palette)
elif hasattr(qualitative, palette):
function_name = getattr(qualitative, palette)
elif hasattr(sequential, palette):
function_name = getattr(sequential, palette)
else:
function_name = diverging.Spectral_11 # Default palette
palette_orientation = "-"
hexcodes = function_name.hex_colors
# Adjust palette orientation
if palette in diverging.__dict__:
palette_orientation = "-" if palette_orientation == "+" else "+"
new_hexcodes = hexcodes[::-1] if palette_orientation == "-" else hexcodes
if colors:
new_hexcodes = colors # Override colors if provided
if not xlim:
xlim = 0
# Determine maximum genomic position for scaling
max_val = max(sdf["q_en"].max(), sdf["r_en"].max(), xlim)
# If user provides breaks, convert to ints
if not breaks:
breaks = generate_breaks(int(max_val))
else:
[int(x) for x in breaks]
xlim = xlim or 0
# Compute window size (handling exceptions)
try:
window = max(sdf["q_en"] - sdf["q_st"])
except ValueError: # Empty dataframe case
return ggplot(aes(x=[], y=[])) + theme_minimal()
# Determine axis label scale based on genomic position size
if max_val < 200_000:
x_label = "Genomic Position (Kbp)"
elif max_val < 200_000_000:
x_label = "Genomic Position (Mbp)"
else:
x_label = "Genomic Position (Gbp)"
# Create the plot
common_theme = theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_ticks_major=element_line(
size=(width), color="black"
), # Increased tick length
title=element_text(
family=["DejaVu Sans"], size=title_length, hjust=0.5
), # Center title
axis_title_x=element_text(size=(width * 1.4), family=["DejaVu Sans"]),
strip_background=element_blank(), # Remove facet strip background
strip_text=element_text(
size=(width * 1.2), family=["DejaVu Sans"]
), # Customize facet label text size (optional)
)
# Construct the plot arguments
ggplot_args = (
ggplot(sdf)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ common_theme
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ facet_grid("r ~ q")
+ labs(x=x_label, y="", title=title_name)
)
# Select either geom_raster or geom_tile depending on deraster flag
p = ggplot_args + (geom_tile if deraster else geom_raster)(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window)
)
return p
def make_dot_grid(
sdf,
title_name,
palette,
palette_orientation,
colors,
breaks,
on_diagonal,
xlim,
deraster,
width,
):
# Select the color palette
if hasattr(diverging, palette):
function_name = getattr(diverging, palette)
elif hasattr(qualitative, palette):
function_name = getattr(qualitative, palette)
elif hasattr(sequential, palette):
function_name = getattr(sequential, palette)
else:
function_name = diverging.Spectral_11 # Default palette
palette_orientation = "-"
hexcodes = function_name.hex_colors
# Adjust palette orientation
if palette in diverging.__dict__:
palette_orientation = "-" if palette_orientation == "+" else "+"
new_hexcodes = hexcodes[::-1] if palette_orientation == "-" else hexcodes
if colors:
new_hexcodes = colors # Override colors if provided
if not xlim:
xlim = 0
# Determine maximum genomic position for scaling
max_val = max(sdf["q_en"].max(), sdf["r_en"].max(), xlim)
# If user provides breaks, convert to ints
if not breaks:
breaks = generate_breaks(int(max_val))
else:
[int(x) for x in breaks]
xlim = xlim or 0
# Compute window size (handling exceptions)
try:
window = max(sdf["q_en"] - sdf["q_st"])
except ValueError: # Empty dataframe case
return ggplot(aes(x=[], y=[])) + theme_minimal()
# Determine axis label scale based on genomic position size
if max_val < 200_000:
x_label = "Genomic Position (Kbp)"
elif max_val < 200_000_000:
x_label = "Genomic Position (Mbp)"
else:
x_label = "Genomic Position (Gbp)"
# Create the plot
common_theme = theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_ticks_major=element_line(
size=(width), color="black"
), # Increased tick length
title=element_text(size=(width * 1.2), alpha=0),
axis_title_x=element_text(size=(width * 1.2), family=["DejaVu Sans"]),
strip_background=element_blank(), # Remove facet strip background
strip_text=element_text(
size=(width * 1.2), family=["DejaVu Sans"]
), # Customize facet label text size (optional)
)
# Construct the plot arguments
ggplot_args = (
ggplot(sdf)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ common_theme
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x="", y="", title="")
)
# Select either geom_raster or geom_tile depending on deraster flag
p = ggplot_args + (geom_tile if deraster else geom_raster)(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window)
)
return p
def make_dot_final(
sdf,
width,
palette,
palette_orientation,
colors,
breaks,
xlim,
transpose=False,
deraster=False,
):
if hasattr(diverging, palette):
function_name = getattr(diverging, palette)
elif hasattr(qualitative, palette):
function_name = getattr(qualitative, palette)
elif hasattr(sequential, palette):
function_name = getattr(sequential, palette)
else:
function_name = diverging.Spectral_11 # Default palette
palette_orientation = "-"
hexcodes = function_name.hex_colors
# Adjust palette orientation
if palette in diverging.__dict__:
palette_orientation = "-" if palette_orientation == "+" else "+"
new_hexcodes = hexcodes[::-1] if palette_orientation == "-" else hexcodes
if colors:
new_hexcodes = colors # Override colors if provided
if not xlim:
xlim = 0
# Determine maximum genomic position for scaling
max_val = max(sdf["q_en"].max(), sdf["r_en"].max(), xlim)
# If user provides breaks, convert to ints
if not breaks:
breaks = generate_breaks(int(max_val))
else:
[int(x) for x in breaks]
xlim = xlim or 0
max_val = max(sdf["q_en"].max(), sdf["r_en"].max(), xlim)
try:
window = max(sdf["q_en"] - sdf["q_st"])
except:
p = (
ggplot(aes(x=[], y=[]))
+ theme_minimal()
+ theme(
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
)
)
return p
x_col, y_col = ("r_st", "q_st") if transpose else ("q_st", "r_st")
if deraster:
p = (
ggplot(sdf)
+ geom_tile(
aes(x=x_col, y=y_col, fill="discrete", height=window, width=window)
)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_ticks_major=element_line(),
title=element_text(family=["Dejavu Sans"]),
)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x=None, y=None, title=None)
)
else:
p = (
ggplot(sdf)
+ geom_raster(
aes(x=x_col, y=y_col, fill="discrete", height=window, width=window)
)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_ticks_major=element_line(),
title=element_text(family=["Dejavu Sans"]),
)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x=None, y=None, title=None)
)
p += theme(axis_title_x=element_blank(), axis_title_y=element_blank())
return p
def make_tri(
sdf,
title_name,
palette,
palette_orientation,
colors,
breaks,
xlim,
num_ticks,
deraster,
width,
):
# Select the color palette
if hasattr(diverging, palette):
function_name = getattr(diverging, palette)
elif hasattr(qualitative, palette):
function_name = getattr(qualitative, palette)
elif hasattr(sequential, palette):
function_name = getattr(sequential, palette)
else:
function_name = diverging.Spectral_11 # Default palette
palette_orientation = "-"
hexcodes = function_name.hex_colors
# Adjust palette orientation
if palette in diverging.__dict__:
palette_orientation = "-" if palette_orientation == "+" else "+"
new_hexcodes = hexcodes[::-1] if palette_orientation == "-" else hexcodes
if colors:
new_hexcodes = colors # Override colors if provided
if not xlim:
xlim = 0
# Determine maximum genomic position for scaling
max_val = max(sdf["q_en"].max(), sdf["r_en"].max(), xlim)
# If user provides breaks, convert to ints
if not breaks:
breaks = generate_breaks(int(max_val))
else:
[int(x) for x in breaks]
xlim = xlim or 0
# Compute window size (handling exceptions)
try:
window = max(sdf["q_en"] - sdf["q_st"])
except ValueError: # Empty dataframe case
return ggplot(aes(x=[], y=[])) + theme_minimal()
# Determine axis label scale based on genomic position size
if max_val < 200_000:
x_label = "Genomic Position (Kbp)"
elif max_val < 200_000_000:
x_label = "Genomic Position (Mbp)"
else:
x_label = "Genomic Position (Gbp)"
if not deraster:
tri = (
ggplot(sdf)
+ geom_raster(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window),
alpha=1.0,
) # Ensure full opacity
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ scale_color_discrete(guide=False)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x=x_label, y="", title=title_name)
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_line_x=element_line(),
axis_line_y=element_blank(),
axis_ticks_major_x=element_line(),
axis_ticks_major_y=element_blank(),
axis_ticks_major=element_line(size=(width)),
title=element_text(size=(width * 1.4), hjust=0.5),
axis_title_x=element_text(size=(width * 1.4), family=["DejaVu Sans"]),
axis_text_y=element_blank(),
)
)
axis = (
ggplot(sdf)
+ geom_tile(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window),
alpha=0,
)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x="", y="", title=title_name)
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_ticks_major=element_line(),
axis_line_x=element_line(),
axis_line_y=element_blank(),
axis_ticks_major_x=element_line(),
axis_ticks_major_y=element_blank(),
axis_text_x=element_line(),
axis_text_y=element_blank(),
plot_title=element_blank(),
axis_title_x=element_text(size=(width * 1.2), family=["DejaVu Sans"]),
)
)
else:
tri = (
ggplot(sdf)
+ geom_tile(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window),
alpha=1.0,
) # Ensure full opacity
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ scale_color_discrete(guide=False)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x=x_label, y="", title=title_name)
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_text=element_text(family=["DejaVu Sans"], size=width),
axis_line_x=element_line(),
axis_line_y=element_blank(),
axis_ticks_major_x=element_line(),
axis_ticks_major_y=element_blank(),
axis_ticks_major=element_line(),
axis_text_y=element_blank(),
title=element_blank(),
axis_title_x=element_text(size=(width * 1.2), family=["DejaVu Sans"]),
)
)
axis = (
ggplot(sdf)
+ geom_tile(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window),
alpha=0,
)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(values=new_hexcodes, guide=False)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x="", y="", title="")
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"),
axis_text=element_text(family=["DejaVu Sans"]),
axis_ticks_major=element_line(),
axis_line_x=element_line(),
axis_line_y=element_blank(),
axis_ticks_major_x=element_line(),
axis_ticks_major_y=element_blank(),
axis_text_x=element_line(),
axis_text_y=element_blank(),
plot_title=element_blank(),
axis_title_x=element_text(size=(width * 1.2), family=["DejaVu Sans"]),
)
)
return tri, axis
def rotate_vectorized_tri(svg_path, scale_x, scale_y):
# Define SVG namespace
ns = {"svg": "http://www.w3.org/2000/svg"}
# Parse the SVG file
tree = ET.parse(svg_path)
root = tree.getroot()
# Find all <g> elements with id="PolyCollection_1"
g_elements = root.find(".//svg:g[@id='PolyCollection_1']", namespaces=ns)
if g_elements is not None:
# Apply the rotation transform to the group
scale_factor = 1 / math.sqrt(2)
transform = f"rotate(45 0 0) translate({scale_x}, {scale_y}) scale({scale_factor}, {scale_factor})"
g_elements.set("transform", transform)
# Save the modified SVG
viewBox = root.get("viewBox")
if viewBox:
min_x, min_y, width, height = map(float, viewBox.split())
new_min_y = min_y + height / 2 # Move down by half the height
new_height = height / 2 # Reduce height by half
root.set("viewBox", f"{min_x} {new_min_y} {width} {new_height}")
else:
print("No viewBox found. Consider adding one manually.")
# Hacky, but it works to halve the height
height_svg = root.get("height")
if height_svg:
current_height = re.match(r"(\d*\.?\d+)([a-zA-Z%]*)", height_svg)
if current_height:
numeric_height, unit = current_height.groups()
numeric_height = float(numeric_height)
root.set("height", f"{numeric_height / 1.8}pt")
tree.write(svg_path)
def rotate_rasterized_tri(svg_path, shift_x, shift_y):
# Load the SVG file
tree = ET.parse(svg_path)
root = tree.getroot()
# Namespace handling
ns = {"svg": "http://www.w3.org/2000/svg"}
# Find all image elements with base64 embedded data
for image in root.findall(".//svg:image", ns):
href = image.get("{http://www.w3.org/1999/xlink}href", "")
if href.startswith("data:image/png;base64,"):
# Get the current width and height of the image
width = float(image.get("width", 0)) / math.sqrt(2)
height = float(image.get("height", 0)) / math.sqrt(2)
# Set the new width and height
image.set("width", str(width))
image.set("height", str(height))
# Apply a 270-degree rotation (about the top-left corner of the image)
transform = image.get("transform", "")
new_transform = (
f"rotate(45, 0, 0) translate({shift_x}, {shift_y}) {transform}"
if transform
else f"rotate(45, 0, {height}) translate({shift_x}, {shift_y})"
)
image.set("transform", new_transform)
# Update viewbox
viewBox = root.get("viewBox")
if viewBox:
min_x, min_y, width, height = map(float, viewBox.split())
new_min_y = min_y + height / 2 # Move down by half the height
new_height = height / 2 # Reduce height by half
root.set("viewBox", f"{min_x} {new_min_y} {width} {new_height}")
else:
print("No viewBox found. Consider adding one manually.")
# Hacky, but it works to halve the height
height_svg = root.get("height")
if height_svg:
current_height = re.match(r"(\d*\.?\d+)([a-zA-Z%]*)", height_svg)
if current_height:
numeric_height, unit = current_height.groups()
numeric_height = float(numeric_height)
root.set("height", f"{numeric_height / 1.8}pt")
else:
print("Warning: Could not parse height attribute.")
# Save the modified SVG back to the same file
tree.write(svg_path)
def make_tri_axis(sdf, title_name, palette, palette_orientation, colors, breaks, xlim):
if not breaks:
breaks = True
else:
breaks = [float(number) for number in breaks]
if not xlim:
xlim = 0
hexcodes = []
new_hexcodes = []
if palette in DIVERGING_PALETTES:
function_name = getattr(diverging, palette)
hexcodes = function_name.hex_colors
if palette_orientation == "+":
palette_orientation = "-"
else:
palette_orientation = "+"
elif palette in QUALITATIVE_PALETTES:
function_name = getattr(qualitative, palette)
hexcodes = function_name.hex_colors
elif palette in SEQUENTIAL_PALETTES:
function_name = getattr(sequential, palette)
hexcodes = function_name.hex_colors
else:
function_name = getattr(sequential, "Spectral_11")
palette_orientation = "-"
hexcodes = function_name.hex_colors
if palette_orientation == "-":
new_hexcodes = hexcodes[::-1]
else:
new_hexcodes = hexcodes
if colors:
new_hexcodes = colors
max_val = max(sdf["q_en"].max(), sdf["r_en"].max(), xlim)
window = max(sdf["q_en"] - sdf["q_st"])
if max_val < 100000:
x_label = "Genomic Position (Kbp)"
elif max_val < 100000000:
x_label = "Genomic Position (Mbp)"
else:
x_label = "Genomic Position (Gbp)"
p = (
ggplot(sdf)
+ geom_tile(
aes(x="q_st", y="r_st", fill="discrete", height=window, width=window),
alpha=0,
)
+ scale_color_discrete(guide=False)
+ scale_fill_manual(
values=new_hexcodes,
guide=False,
)
+ theme(
legend_position="none",
panel_grid_major=element_blank(),
panel_grid_minor=element_blank(),
plot_background=element_blank(),
panel_background=element_blank(),
axis_line=element_line(color="black"), # Adjust axis line size
axis_text=element_text(
family=["DejaVu Sans"]
), # Change axis text font and size
axis_ticks_major=element_line(),
axis_line_x=element_line(), # Keep the x-axis line
axis_line_y=element_blank(), # Remove the y-axis line
axis_ticks_major_x=element_line(), # Keep x-axis ticks
axis_ticks_major_y=element_blank(), # Remove y-axis ticks
axis_text_x=element_line(), # Keep x-axis text
axis_text_y=element_blank(),
plot_title=element_blank(),
)
+ scale_x_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ scale_y_continuous(labels=make_scale, limits=[0, max_val], breaks=breaks)
+ coord_fixed(ratio=1)
+ labs(x="", y="", title=title_name)
)
# Adjust x-axis label size
p += theme(axis_title_x=element_text())
return p
def make_hist(sdf, palette, palette_orientation, custom_colors, custom_breakpoints):
hexcodes = []
new_hexcodes = []
if palette in DIVERGING_PALETTES:
function_name = getattr(diverging, palette)
hexcodes = function_name.hex_colors
if palette_orientation == "+":
palette_orientation = "-"
else:
palette_orientation = "+"
elif palette in QUALITATIVE_PALETTES:
function_name = getattr(qualitative, palette)
hexcodes = function_name.hex_colors
elif palette in SEQUENTIAL_PALETTES:
function_name = getattr(sequential, palette)
hexcodes = function_name.hex_colors
else: